<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch',  'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('chat.userChat.quick Search Fields') })"
        ></TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef"></Table>

        <!-- 表单 -->
        <PopupForm />


        <el-dialog
            v-model="chat_show"
            title="留言板"
            width="500"
            :draggable="true"

        >

            <div class="chat-container">
                <!-- 消息列表 -->
                <div class="message-list" ref="messageList">
                    <div
                        v-for="(message, index) in messages"
                        :key="index"

                    >
                        <p  :class="[ message.type == 1 ? 'user-message1' : 'bot-message1']" >{{message.nickname}} {{message.create_time_text}}</p>
                        <div class="message-content" :class="['message', message.type == 1 ? 'user-message' : 'bot-message']">
                            {{ message.content }}
                        </div>

                    </div>
                </div>

                <!-- 输入框 -->
                <div class="input-container">
                    <input
                        v-model="newMessage"
                        type="text"
                        placeholder="请输入消息内容"
                        @keyup.enter="sendMessage"
                    />
                    <button @click="sendMessage">发送</button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import moment from "moment/moment";
import {useAdminInfo} from "/@/stores/adminInfo";
import createAxios from "/@/utils/axios";
import {ElMessage} from "element-plus";

defineOptions({
    name: 'chat/userChat',
})

const { t } = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])

optButtons.push(
    {
        render: 'tipButton',
        // name 是任意的
        name: 'info',
        // title 是语言翻译 key
        title: '留言板',
        text: '',
        // type: 'warning',
        // icon: 'fa fa-search-plus icon',
        type: 'success',
        icon: 'el-icon-ChatDotSquare',
        click(row, field) {
            chat_show_act(row.id);
        },
        display(row, field) {
            if (row.admin_unread  <= 0){
                return true;
            }else{
                return false;
            }
        },

    },
    {
        render: 'tipButton',
        // name 是任意的
        name: 'info',
        // title 是语言翻译 key
        title: '留言板',
        text: '',
        // type: 'warning',
        // icon: 'fa fa-search-plus icon',
        type: 'primary',
        icon: 'el-icon-ChatDotSquare',
        click(row, field) {
            chat_show_act(row.id);
        },
        display(row, field) {
            if (row.admin_unread  > 0){
                return true;
            }else{
                return false;
            }
        },

    },
)
/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/chat.UserChat/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('chat.userChat.id'), prop: 'id', align: 'center', width: 150, operator: 'RANGE', sortable: false },
            { label: t('chat.userChat.user_id'), prop: 'user_id', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            { label: t('chat.userChat.user__nickname'), prop: 'user.nickname', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE' },
            { label: t('chat.userChat.user__mobile'), prop: 'user.mobile', align: 'center', operatorPlaceholder: t('Fuzzy query'),  operator: 'LIKE' },
            // { label: t('chat.userChat.user_unread'), prop: 'user_unread', align: 'center', operator: 'RANGE', sortable: false },
            // { label: t('chat.userChat.admin_unread'), prop: 'admin_unread', align: 'center', operator:false, sortable: 'custom' },
            // { label: t('chat.userChat.create_time'), prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('chat.userChat.update_time'), prop: 'update_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: true, width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: ['all'],
        defaultOrder: { prop: 'update_time', order: 'desc' },
    },
    {
        defaultItems: { user_unread: 0, admin_unread: 0 },
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})


const chat_show = ref(false)


const messages = ref([

]);
const newMessage = ref("");
const user_chat_id = ref(0);
const sendMessage = () => {
    if (newMessage.value.trim() !== "") {
        const create_msg_data = ref({})
        create_msg_data.value = {user_chat_id:user_chat_id.value,type: "1", create_time_text: moment().format('YYYY-MM-DD HH:mm:ss'), nickname: useAdminInfo().nickname, content: newMessage.value }
        messages.value.push(create_msg_data.value);
        newMessage.value = "";

        setTimeout(function () {
            scrollToBottom();
        })

        // 提交保存
        createAxios({
            url: '/admin/chat.UserChatLog/add_log_ajax',
            method: 'post',
            data: create_msg_data.value
        },{
            loading:false
        },{
            text: ''
        })
            .then((res) => {
                if (res.code == 1){
                }else {
                    ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
            .catch((resx) => {
            })

    }
};

const messageList = ref("messageList");
const scrollToBottom = () => {
    messageList.value.scrollTop = messageList.value.scrollHeight;
};


const chat_show_act = (id) => {


    if (id > 0){
        user_chat_id.value = id;
        createAxios({
            url: '/admin/chat.UserChatLog/index_ajax',
            method: 'post',
            data: {id:id}
        },{
            loading:true
        },{
            text: '获取留言记录...'
        })
            .then((res) => {
                if (res.code == 1){
                    messages.value = res.data;
                    chat_show.value = true;
                    setTimeout(function () {
                        scrollToBottom();
                    })

                }else {
                    ElMessage({
                        message: res.msg,
                        type: 'error',
                    })
                }
            })
            .catch((resx) => {
            })
    }
}

</script>

<style scoped lang="scss">
.chat-container {
    width: 100%;
    max-width: 500px;
    height: 550px;
    border: 1px solid #ccc;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    overflow: hidden;
}

.message-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background-color: #f9f9f9;
}

.message {
    margin-bottom: 10px;
    padding: 5px 10px;
    border-radius: 5px;
    max-width: 70%;
    word-wrap: break-word;
}

.user-message {
    background-color: #00a6ff;
    color: white;
    align-self: flex-end;
    margin-left: 150px;
}

.user-message1 {
    text-align: right;

}

.bot-message {
    background-color: #e5e4e4;
    color: black;
    align-self: flex-start;
}

.input-container {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ccc;
}

.input-container input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-right: 10px;
}

.input-container button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.input-container button:hover {
    background-color: #0056b3;
}
</style>
